
#include <iostream>
#include <fstream>
#include "contact.pb.h"

using namespace std;

void AddPeopleInfo(contacts2::PeopleInfo *people)
{
    cout << "--------新增联系人--------" << endl;
    string name;
    cout << "请输入联系人的姓名：";
    getline(cin, name);
    people->set_name(name);
    cout << "请输入联系人的年龄：";
    int age;
    cin >> age;
    people->set_age(age);
    cin.ignore(256, '\n');
    for (int i = 0;; i++)
    {
        cout << "请输入联系人电话" << i + 1 << ": ";
        string num;
        getline(cin, num);
        if (num.empty())
        {
            break;
        }
        contacts2::PeopleInfo_Phone *phone = people->add_phone();
        phone->set_num(num);
    }
    cout << "---------新增联系人成功-------" << endl;
}

int main()
{
    contacts2::Contacts contacts;

    // 1. 将本地联系人文件读取进通讯录
    fstream input("contacts.bin", ios::in | ios::binary); // 如果打开成功就读入，打开失败会帮我新建文件
    if (!input)
    {
        cout << "contacts.bin not find, create new file!" << endl;
    }
    else if (!contacts.ParseFromIstream(&input))
    {
        cerr << "parse error!" << endl;
        input.close();
        return -1;
    }

    // 2. 新增一个联系人
    AddPeopleInfo(contacts.add_contact());
    // 3  将新的通讯录覆盖写回文件
    fstream output("contacts.bin", ios::out | ios::trunc | ios::binary); // trunc清空原本，覆盖写
    if (!contacts.SerializeToOstream(&output))
    {
        cerr << "write failed!" << endl;
        input.close();
        output.close();
        return -1;
    }
    cout << "write successful!" << endl;
    input.close();
    output.close();
    return 0;
}